import { ProColumns, ProTable } from '@ant-design/pro-table';
import { Divider, message, Modal, Popconfirm, Typography } from 'antd';
import React, { PropsWithChildren, useRef, useState } from 'react';
import { ActionType } from '@ant-design/pro-components';
import {
  captainLetTeam,
  kickTeam,
  listMemberTeam,
} from '@/services/teamService';
import { Space } from 'antd/es';
import { UserType } from '@/models/user';
import { TeamType } from '@/models/team';

interface QueryModalProps {
  modalVisible: boolean;
  columns: ProColumns<UserType.User>[];
  onSubmit: () => void;
  onCancel: () => void;
  loginUser: UserType.UserVO;
  allMember: number;
}

/**
 * 队长转让
 * @constructor
 * @param userId
 * @param teamId
 */
const captainLet = async (userId: number, teamId: number) => {
  if (userId <= 0) {
    message.loading('请先进行登入！');
    return [];
  }
  const hide = message.loading('转让中');
  try {
    await captainLetTeam({ userId, teamId });
    message.success('转让成功');
  } catch (error) {
    hide();
    message.success('转让失败请重试');
  } finally {
    hide();
  }
};

/**
 * 踢出队伍
 * @constructor
 * @param userId
 * @param teamId
 * @param captainId
 */
const kick = async (userId: number, teamId: number, captainId: number) => {
  const hide = message.loading('踢出中');
  try {
    await kickTeam({ userId, teamId, captainId });
    message.success('踢出成功');
  } catch (error) {
    hide();
    message.success('踢出失败');
  } finally {
    hide();
  }
};

const QueryModel: React.FC<PropsWithChildren<QueryModalProps>> = (props) => {
  const { modalVisible, allMember, onCancel, loginUser } = props;
  const actionRef = useRef<ActionType>();
  const [model, setModel] = useState<TeamType.TeamVo>();

  const columns: ProColumns<UserType.User>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '用户昵称',
      dataIndex: 'userName',
      valueType: 'text',
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      valueType: 'text',
    },
    {
      title: '用户头像',
      dataIndex: 'avatarUrl',
      valueType: 'image',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      hideInForm: false,
      valueEnum: {
        0: { text: '男' },
        1: { text: '女' },
      },
    },
    {
      title: '用户邮箱',
      dataIndex: 'email',
      valueType: 'text',
    },
    {
      title: '用户电话',
      dataIndex: 'phone',
      valueType: 'text',
    },
    {
      title: '用户个人介绍',
      dataIndex: 'userProfile',
      valueType: 'text',
    },
    {
      title: '账号状态',
      dataIndex: 'userStatus',
      hideInForm: false,
      valueEnum: {
        0: { text: '正常' },
        1: { text: '封号' },
      },
    },
    {
      title: '用户个人信用',
      dataIndex: 'creditsNum',
      valueType: 'text',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space
          style={{ display: model?.userId !== loginUser.id ? 'none' : 'block' }}
          split={<Divider type="vertical" />}
        >
          <Popconfirm
            title="你确定要将队长转让给他？"
            onConfirm={() =>
              captainLet(record?.id || 0, model?.id || 0).then(() => {
                actionRef?.current?.reload();
              })
            }
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link
              type="danger"
              style={{ display: loginUser.id === record.id ? 'none' : 'block' }}
            >
              队长转让
            </Typography.Link>
          </Popconfirm>
          <Popconfirm
            title="你确定要踢出？"
            onConfirm={() => {
              kick(record?.id || 0, model?.id || 0, loginUser.id || 0).then(
                () => {
                  actionRef?.current?.reload();
                },
              );
            }}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link
              type="danger"
              style={{ display: loginUser.id === record.id ? 'none' : 'block' }}
            >
              踢出
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
      width={'80%'}
    >
      <ProTable<UserType.User>
        headerTitle="用户管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        request={async () => {
          const { data, code } = await listMemberTeam(allMember);
          setModel(data);
          return {
            data: data?.member || [],
            success: code === 0,
          } as any;
        }}
        columns={columns}
      />
    </Modal>
  );
};

export default QueryModel;
